<template>
  <div class="app-container">
    <h3>菜单</h3>
    <Tree
      v-model:checkedKeys="checkedKeys"
      checkable
      :tree-data="treeData"
      :field-names="fieldNames"
      :default-expand-all="true"
    />
    <Divider />

    <h3>权限</h3>
    <Tree
      v-model:checkedKeys="checkedKeys2"
      checkable
      :tree-data="treeData2"
      :fieldNames="fieldNames2"
    />

    <Divider />
    <a-button type="primary" @click="onSubmit">提交</a-button>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Tree, Divider } from 'ant-design-vue'
  import { update } from '/@/api/sys/role'
  import { treeAll, listByRole as listMenuByRole } from '/@/api/sys/menu'
  import { all, listByRole as listPerByRole } from '/@/api/sys/permission'
  import { sortBy } from 'lodash-es'

  const emit = defineEmits(['onSuccess'])

  const prop = defineProps({
    roleId: String,
  })

  const fieldNames = { children: 'children', title: 'title', key: 'id' }
  const fieldNames2 = { children: 'children', title: 'name', key: 'id' }

  const checkedKeys = ref([])
  const treeData = ref([])

  const convert = (list) => {
    let result = list.filter((e) => !e.parentId)
    result = sortBy(result, ['menuOrder'])
    reuse(result, list)
    return result
  }

  const reuse = (list, all) => {
    list.forEach((e) => {
      let cList = all.filter((e2) => e2.parentId === e.id)
      e.children = cList
      if (cList) {
        cList = sortBy(cList, ['menuOrder'])
        reuse(cList, all)
      }
    })
  }

  const checkedKeys2 = ref([])
  const treeData2 = ref([])

  onMounted(() => {
    treeAll().then((res) => {
      treeData.value = convert(res)
    })
    prop.roleId &&
      listMenuByRole(prop.roleId).then((res) => {
        checkedKeys.value = res.map((e) => e.id)
      })
    all().then((res) => {
      res.forEach((e) => {
        e.name = `${e.name}-${e.mark}`
      })
      treeData2.value = res
    })

    prop.roleId &&
      listPerByRole(prop.roleId).then((res) => {
        checkedKeys2.value = res.map((e) => e.id)
      })
  })

  const formState = ref<any>({
    permissionIdList: [],
    menuIdList: [],
    id: prop.roleId,
  })

  const btnLoading = ref(false)

  const onSubmit = () => {
    btnLoading.value = true

    formState.value.menuIdList = checkedKeys.value
    formState.value.permissionIdList = checkedKeys2.value

    update(formState.value).then(() => {
      btnLoading.value = false
      emit('onSuccess')
    })
  }
</script>
